package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: lx
 * @Time: 10:40
 * @Description:
 */
@Service
public class TestServiceImpl  implements TestService {

    @Autowired
    private RedisTemplate redisTemplate;
    private final Lock lock = new ReentrantLock();//本地锁 是有局限的  当在集群情况下
    //++
    public void incr(){
        lock.lock();
        try {
            Integer num = (Integer) redisTemplate.opsForValue().get("num");
            num++;
            redisTemplate.opsForValue().set("num",num);
        } finally {
            lock.unlock();
        }
    }
    //分布式锁
    public void incr123(){
        //以线程为单位  不同线程之间 不要误删除锁
        String uuid = UUID.randomUUID().toString();
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("lock", uuid,
                2, TimeUnit.SECONDS);
        // 1: true 0:false
        if(aBoolean){
            //获取到了锁
            try {
                Integer num = (Integer) redisTemplate.opsForValue().get("num");
                num++;
                redisTemplate.opsForValue().set("num",num);//ab 5000  100
                //int i = 1/0;  硬件完蛋
            } finally {
                //先判断是否是自己的锁  LUA脚本 C语言写的  Redis也是C语言写
   /*             Object u = redisTemplate.opsForValue().get("lock");
                if(uuid.equals(u)){
                    //删除掉锁
                    redisTemplate.delete("lock");//死锁  误删
                }*/
                //使用LUA脚本 解决删除原子性问题
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList("lock"), uuid);
                // Redis 是原子性操作？ 原子性操作
            }

        }else{
            //未获取到锁  重试一次
            incr123(); //JUC 过期不候  不见不散
        }

    }
}
